package com.kefu.chat.smart.condition;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.kefu.chat.smart.ChatConnectCondition;
import com.kefu.chat.vo.ChatUserParam.UserConnectP;
import com.kefu.chat.vo.ChatUserParam.UserConnectR;
import com.kefu.common.trigger.Condition;
import com.kefu.common.trigger.Decision;
import com.kefu.common.trigger.TriggerWrapper;
import com.kefu.common.trigger.model.ConditionModel;
import com.kefu.common.trigger.model.DynamicModel;
import com.kefu.common.trigger.model.DynamicModel.OptionType;
import com.kefu.common.trigger.model.DynamicModel.SearchType;
import com.kefu.common.trigger.model.Validator;

@Component
public class ChatChannelTypeCondition implements ChatConnectCondition<Integer> {

	@Override
	public String getCode() {
		return "channel_type";
	}

	@Override
	public ConditionModel getConditionModel() {
		Map<String,String> params=Maps.newHashMap();
		params.put("channelType", "{code}");
		DynamicModel<ConditionModel> dynamicModel=DynamicModel.<ConditionModel>builder()
										.url("chat/channel/list")
										.code("channelId")
										.name("channelName")
										.params(params)
										.validator(Lists.newArrayList(Validator.AllowEmpty))
										.searchType(SearchType.Page)
										.build();
		return ConditionModel.builder()
				.code(getCode())
				.name(getMessageName())
				.optionType(OptionType.Simple)
				.children(conditionModelList(getMessageCodePrefix(),new String[][]{{"1","桌面网站"},{"2","移动网站"},{"3","SDK"},{"4","微信公众号"},{"5","微信小程序"},{"6","企业微信"}},dynamicModel,Lists.newArrayList(Decision.EQ)))
				.build();
	}

	@Override
	public String getName() {
		return "渠道类型";
	}

	@Override
	public boolean match(TriggerWrapper<UserConnectP, UserConnectR> wrapper, Condition condition) {
		String channelType=condition.getSubCondition();
		String channelId=condition.getOperatorValue();
		if(StringUtils.isAllBlank(channelId)) {
			List<Integer> list=Lists.newArrayList(Integer.parseInt(channelType));
			
			return getChatUser(wrapper)!=null&&condition.getDecision().match(list, getChatUser(wrapper).getChannelType(),null);
		}else {
			List<String> list=Lists.newArrayList(channelId);
			return getChatUser(wrapper)!=null&&condition.getDecision().match(list, getChatUser(wrapper).getChannelId(),null);
		}
	}

}
